import { Component, OnInit, ViewChild, Input, Output, EventEmitter, ElementRef } from '@angular/core';
import { Service } from '../../server/server';
import { HttpClient } from '@angular/common/http';
import { HintsService } from '../../public/serve/hints/hints.service';
import { InternalIndexedTableComponent } from '../internal-indexed-table/internal-indexed-table.component';
import { CudTableService } from 'app/public/serve/cud-table/cud-table.service';
import { internal } from '../internal.data';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { InternalIndexedModalTableVersionComponent } from '../internal-indexed-modal-table-version/internal-indexed-modal-table-version.component';
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';
import { LeftKeywordComponent } from './left-keyword/left-keyword.component';
declare var $: any;

@Component({
    selector: 'app-internal-indexing-task',
    templateUrl: './internal-indexing-task.component.html',
    styleUrls: ['./internal-indexing-task.component.css']
})
export class InternalIndexingTaskComponent implements OnInit {

    content = 'Vivamus sagittis lacus vel augue laoreet rutrum faucibus.';
    currentPageX = 0;
    currentPageY = 0;
    completeStatus: string;
    currentTabIndex = 1;
    public idxRefTaskThemeTableList :any;
    public TaskThemeTableList :any;
    isActive = false;
    id: string;
    taskType: any;
    themeTableId: string;
    themeTableName: string;
    themeGroupId: string;
    isTaskCheckBy:boolean = false; //当前用户是否是审核人
    isTaskAssignBy:boolean = false; //当前用户是否是标引人
    internalTablesParam = {
        productType:0,
        taskId: "",
        productId: "",
        themeTableId: "",
        themeTableName: "",
        themeGroupId: "",
        id: "",
        completeStatus:"",
        templateId:"",
        statusData:"",
        checkStatusData:""
    };
    filePath: SafeResourceUrl;
    internalInfo = {
        productType: 0,
        name: '',
        taskId: '',
        productId: '',
        status: '',
        checkStatus: '',
        fileContent: '',
        refIndexing: '',
        idxProduct: null,

        idxTaskThemeTableList: null,
        idxThemeTable:null,
        templateId:''
    };
    right: any = {
        "indexingTaskList":{},
        "productIndexingTask": {},
        "internalIndexingTask": {},
        "themeContentIndexing": {},
    };
    public internalThemeWordsLeftEmit: any;
    public internalDeleteContentsEmit: any;
    public internalRightModalEmit: any;
    public internalTimeAttributeEmit:any;
    constructor(private hostElement: ElementRef, private sanitizer: DomSanitizer, private activatedRoute: ActivatedRoute, private server: Service, private http: HttpClient, private hintsService: HintsService, public request: CudTableService, public router: Router) {
        this.filePath = this.sanitizer.bypassSecurityTrustResourceUrl('http://www.baidu.com');
        this.right = $.extend(this.right, server.getRight());
    }
    //当前选中主题词
    currentThemeIndexing: string = '';
    internalContent:any = '';
    //文内样式设置
    internalContentStyle = {
        markedRed: '<span style="color:red;" class="indexing_a" data-id="[TID]" data-indexing-name="[INDEXINGNAME]" data-order="[SID]">[CONTENT]</span>',
        highlight: '<span style="background-color:yellow;" class="indexing_a" data-id="[TID]" data-indexing-name="[INDEXINGNAME]" data-order="[SID]">[CONTENT]</span>',
        link: '<a href="#" class="indexing_a" data-id="[TID]" data-indexing-name="[INDEXINGNAME]" data-order="[SID]">[CONTENT]</a>',
    }

    internalContentTag: string = 'markedRed';

    public inputComplete: any;
    public onSubmitAppViewEmit: any;
    taskProductList: Array<object>;

    @Input() statusData: any = 0;
    @Input() checkStatusData: any = 0;
    public currentThemeWordInfo : object;
    fileFormat : any;

    currentSelectedThemeWords = true;

    //导入table
    @ViewChild('table')
    table: InternalIndexedTableComponent;
    @ViewChild('versionTable')
    versionTable: InternalIndexedModalTableVersionComponent;
    @ViewChild("leftKeyword") leftKeyword : LeftKeywordComponent;
    ngOnInit() {
        //已标引的内文主题词 鼠标事件
        let t = this;
        $(document).unbind('mouseover').unbind('mouseout');
        $(document).on('mouseover','.indexing_a',function(e){
            e = e || window.event;
            setTimeout(()=>{
                $(".ng-popver").toggle(100);
                $(".ng-popver").css("top",e.pageY + "px");
                $(".ng-popver").css("left",e.pageX + "px");
            },300);
            let theme_id = $(this).attr('data-id');
            let indexing_id = $(this).attr('data-indexing-id');
            let indexing_name = $(this).attr('data-indexing-name');
            let data_order = $(this).attr('data-order');
            let vals = {
                'id':indexing_id,
                'theme_id':theme_id,
                'indexing_name':indexing_name,
                'data_order':data_order,
            };
            t.server.internalLeftIndexingDeleteEmit.emit(vals);
            
            $('.custom-menu').hide();
        }).on('mouseout','.indexing_a',function(event){
            var div = document.getElementById("ngPopver");
            if(div){
                var x=event.clientX;
                var y=event.clientY;
                var divx1 = div.offsetLeft;
                var divy1 = div.offsetTop;
                var divx2 = div.offsetLeft + div.offsetWidth;
                var divy2 = div.offsetTop + div.offsetHeight;
                if( x < divx1 || x > divx2 || y < divy1 || y > divy2){
                    $(".ng-popver").hide();
                }
            }
        }).on('mouseout','.ng-popver',function(event){
            var div = document.getElementById("ngPopver");
            var x=event.clientX;
            var y=event.clientY;
            var divx1 = div.offsetLeft;
            var divy1 = div.offsetTop;
            var divx2 = div.offsetLeft + div.offsetWidth;
            var divy2 = div.offsetTop + div.offsetHeight;
            if( x < divx1 || x > divx2 || y < divy1 || y > divy2){
                $(".ng-popver").hide();
            }
        });

        this.activatedRoute.queryParams.subscribe((p: Params) => {
            this.id = p['id'];
            this.taskType = p['taskType'];
            this.internalContent = '';
            this.getIndexingDetails();
        });

        //缩放左侧菜单
        //this.server.isActive = false;
        setTimeout(()=>{
            $("#indexingContentBox").find('#contentArea_leftDiv').attr('class','row contentArea_leftDiv left-off');
            $("#indexingContentBox").find('#contentArea_leftDiv').find('#shrink-from').attr('class','shrink-from closec');
            $("#indexingContentBox").find('#contentArea_leftDiv').find('#shrink-from').find('img[class="right-img"]').click();
        },100);
        this.server.eventEmit.subscribe((value: any) => {
            $("#indexingContentBox").find('#contentArea_leftDiv').attr('class','row contentArea_leftDiv left-full');
            $("#indexingContentBox").find('#contentArea_leftDiv').find('#shrink-from').attr('class','shrink-from open');
            this.isActive = value;
        });

        //内文样式获取
        this.getIndexingTag();
        $(function () {
            $('#myTxtTab li:eq(0) a').tab('show');
            $('#myTxtWinTab li:eq(0) a').tab('show');
           // $('#ReferenceIndexingTab li:eq(1) a').tab('show');
           $("#tab_attribute a").attr('class','');
           $("#tab_time_attribute a").attr('class','');
           
           $("#tab1").show();
           $("#tab2").hide();
           $("#tab3").hide();
        });

        //查看主题词确认标引
        this.onSubmitAppViewEmit = this.server.onSubmitAppViewEmit.subscribe((value: any) => {
            if (value) {
                let k = 0;
                for (let val of value) {
                    if (Object.prototype.toString.call(val) === '[object Object]') {
                        k += 1;
                        this.indexingContent(val, k);
                    }
                }
            }
        });

        this.activatedRoute.url.subscribe(r => {
            //权限
            if(this.taskType == 1){
                //内文任务
                this.right['indexingTaskList'] = this.right['internalIndexingTask'];
            }else if(this.taskType == 0){
                //产品任务
                this.right['indexingTaskList'] = this.right['productIndexingTask'];
            }else if(this.taskType == 2){
                //主题词任务
                this.right['indexingTaskList'] = this.right['themeContentIndexing'];
            }
        })

        //树形
        var treeData = [
        ];


        //internalThemeWordsLeftEmit
        this.internalThemeWordsLeftEmit = this.server.internalThemeWordsLeftEmit.subscribe((value: any) => {
            if (value) {
                this.currentThemeWordInfo = value
            }
        });

        //右键标引主题词
        this.internalRightModalEmit = this.server.internalRightModalEmit.subscribe((value: any) => {
            if (value) {
                //'ir' 右侧标引时如果已经存在主题词了，还是要标引，但是不要提示
                this.selectedIndexingContent(value,1,'ir');
                $(".custom-menu").hide();
            }
        });

        //时间属性标引
        this.internalTimeAttributeEmit = this.server.internalTimeAttributeEmit.subscribe((value: any) => {
            if (value) {
                this.timeAttrIndexingContent(value);
            }
        });


        this.internalDeleteContentsEmit = this.server.internalDeleteContentsEmit.subscribe((value: any) => {
            if (value) {
                this._deleteIndexingContent(value);
            }
        });
    }

    //内嵌弹窗
    // _popover(){

    // }

    rightMouseUp(){
        this.setSelectionContents();

    }

    _setmousemove(e) {
        e = e || window.event;
        if(e.pageX || e.pageY) {
            this.currentPageX = e.pageX;
            this.currentPageY = e.pageY
        }
    }

    clearSelectionContents(){
            $('.selected-current-contents').each(function (index,obj) {
                $(obj).prop('outerHTML',$(obj).html());
            });
    }

    setSelectionContents(){

        if (window.getSelection) {
            $('.selected-current-contents').each(function (index,obj) {
                $(obj).prop('outerHTML',$(obj).html());
            });
            let selecter = window.getSelection();

            let selectStr = selecter.toString();
            if (selectStr != "") {
                let rang = selecter.getRangeAt(0);
                let docFragment = rang.cloneContents();
                let tmpDiv = document.createElement("div");
                tmpDiv.appendChild(docFragment);
                let  indexing_a = $(tmpDiv).find('[class="indexing_a"]');
                //只有获取中焦点后才验证是否存在
                // if (document.activeElement.id == "mat-input-1"){
                    if(indexing_a.length > 0){
                        this.hintsService.messages('选中文字中不能包含其他标引主题词', '9999');
                        this.currentSelectedThemeWords = true;
                        return false;
                    }else{
                        this.currentSelectedThemeWords = false;
                    }
                    let selectHtml = tmpDiv.innerHTML;
                    let temp = $("<span class=\"selected-current-contents\" style=\"color:#FFFFFF;background-color: rgb(49,142,252);\">" + selectStr + "<span/>");
                    rang.surroundContents(temp[0]);
                // }
                $(".custom-menu").hide();
                $(".custom-menu").toggle(50).
                css({
                    top: this.currentPageY + "px",
                    left: this.currentPageX + "px"
                });

            }else{
                $(".custom-menu").hide();
                this.currentSelectedThemeWords = false;
            }
        }
    }

    ngOnDestroy() {
        this.onSubmitAppViewEmit ? this.onSubmitAppViewEmit.unsubscribe() : '';
        this.internalThemeWordsLeftEmit ? this.internalThemeWordsLeftEmit.unsubscribe() : '';
        this.internalDeleteContentsEmit ? this.internalDeleteContentsEmit.unsubscribe() : '';
        this.internalTimeAttributeEmit ? this.internalTimeAttributeEmit.unsubscribe() : '';
        this.internalRightModalEmit ? this.internalRightModalEmit.unsubscribe() : '';
    }

    getIndexingTag() {
        let url = this.server.baseUrl + 'Service/Config/getIndexingTag';
        let data = {}
        this.http.post(url, data)
            .subscribe(res => {
                if (res['result_code'] == '0000') {

                    let result = res['result'];
                    if (result) {
                        this.internalContentTag = result[0]['tagName'];
                    }
                } else {
                    this.server.prompt = { prompt: true, success: false, fail: true, promptStatement: res['message'] };
                    this.server.promptclose;
                }
            });
    }

    findThemeContent(val) {
        if (Object.prototype.toString.call(val) === '[object Object]') {
            //直接标引
           if($('.selected-current-contents').length > 0){
               this.selectedIndexingContent(val);
           }else{
               this.indexingContent(val);
           }

        }
    }

    selectedIndexingContent(content: any, k: any = 1,ir:any = ''){
        const themeName = content['txt'];
        const themeID = content['val'];

        let indexing_name = themeName;
        if(this.themeTableName){
            indexing_name = this.themeTableName+'/'+themeName;
        }
        let selectedObj = $('.selected-current-contents');
        let sid = 0;
        if(typeof ($('span[data-id='+themeID+']').attr('data-order')) != undefined){
            let sid_txt = $('span[data-id='+themeID+']').attr('data-order');
            sid = !isNaN(Number(sid_txt)) ? Number(sid_txt) : 0;
            sid = sid + 1;
        }

        selectedObj.prop('outerHTML',this.internalContentStyle[this.internalContentTag].replace('[CONTENT]', selectedObj.html()).replace('[TID]', themeID).replace('[INDEXINGNAME]', indexing_name).replace('[SID]', sid.toString()));
        this.internalContent =  $('#internalContents').html();
        this.addThemeIndexing(themeName, themeID, k,'succ',ir);
    }

    timeAttrIndexingContent(content: any){
        const timeName = content['txt'];
        const timeID = content['val'];

        let indexing_name = '时间属性/'+timeName;
        let selectedObj = $('.selected-current-contents');
        selectedObj.prop('outerHTML',this.internalContentStyle[this.internalContentTag].replace('[CONTENT]', selectedObj.html()).replace('[TID]', timeID).replace('[INDEXINGNAME]', indexing_name));
        this.internalContent =  $('#internalContents').html();
        //保存内文加上标记后的内容
        this._saveProductFileContent(this.internalTablesParam.productId,this.internalContent);
    }

    //标引
    indexingContent(content: any, k: any = 1) {
        const themeName = content['txt'];
        const themeID = content['val'];

        let indexing_name = themeName;
        if(this.themeTableName){
            indexing_name = this.themeTableName+'/'+themeName;
        }

        //产品不需要寻找内容标引
        if (this.taskType == 1) {


            let isIndexing = false;
            if (this.internalContent) {
                let sid = 1;
                while (true) {
                    let isNext = false;
                    let internalContentObj = $('<div>' + this.internalContent + '</div>');
                    if (internalContentObj.length > 0) {
                        internalContentObj.find('*').contents().each((index, item) => {
                            let tagName = $(item).parent().eq(0)[0].tagName;
                            if ($(item).parent().hasClass('indexing_a') === false) {
                                let tmp = item['data'];
                                if (tmp) {
                                    if (tmp.indexOf(themeName) !== -1) {
                                        //标记
                                        internalContentObj.find('*').contents().eq(index)[0].data = internalContentObj.find('*').contents().eq(index)[0].data.replace(themeName, `[@#$%${themeName}@#$%]`);
                                        let internalContentHtml = $(internalContentObj).html();
                                        internalContentHtml = internalContentHtml.replace(`[@#$%${themeName}@#$%]`, this.internalContentStyle[this.internalContentTag].replace('[CONTENT]', themeName).replace('[TID]', themeID).replace('[SID]', sid).replace('[INDEXINGNAME]', indexing_name));
                                        this.internalContent = internalContentHtml;
                                        isIndexing = true;
                                        isNext = true;
                                        sid = sid + 1;
                                        // this.addThemeIndexing(themeName, themeID, k,'succ');
                                        return false;
                                    }
                                }
                            }
                        });
                    }
                    if(!isNext){
                        break;
                    }
                }
                if (isIndexing) {
                    this.addThemeIndexing(themeName, themeID, k,'succ');
                }
            }
            if (!isIndexing) {
                this.addThemeIndexing(themeName, themeID, k);
                //this.hintsService.messages('文章中没有找到['+themeName+']主题词','0000');
            }


        } else if(this.taskType == 0){
            this.addThemeIndexing(themeName, themeID, k);
        }else if(this.taskType == 2){
            this.addThemeRelIndex(themeName, themeID, k);
        }

    }

    //增加关联标引
    addThemeRelIndex(val, id, k: any = 1,succ:any = ''){
       let data = {
            themeTableId  : this.currentThemeWordInfo['themeTableId'],
            themeWordsId  : this.currentThemeWordInfo['themeWordsId'],
            themeWordsName  : this.currentThemeWordInfo['themeWordsName'],
            productId  : this.internalTablesParam.productId,
            taskId  : this.internalTablesParam.taskId,
            relThemeTableId  : this.internalTablesParam.themeTableId,
            relThemeWordsId  : id,
            relThemeWordsNname  : val,
            createBy  : this.server.getuserName()
        };
        let url = this.server.baseUrl +  'Service/IdxProduct/setProductThemeRelation';
        this.request.postRequest(url,data).then((res:any) => {
            if (res.result_code === '0000') {
                //成功只提示一次，k==1 
                if (k === 1) {
                    this.hintsService.messages(`主题词标引成功!`, res['result_code']);
                }

                this.server.internalThemeWordsTablesRelEmit.emit(this.taskType);
            }else if(res.result_code == '9999'){
                if (k === 1) {
                    this.hintsService.messages(res.message,res.result_code);
                }
            } else {
                if (k === 1) {
                    this.hintsService.messages('error', 'error');
                }
            }
            return;
        })
            .catch((err: any)=>{
                this.hintsService.messages("error","error");
                return;
            });
    }

    //普通产品标引
    addThemeIndexing(val, id, k: any = 1,succ:any = '',ir:any = '') {
        let url = this.server.baseUrl + 'Service/IdxProduct/addProductThemeWords';
        let data = {
            "token": "b25dbd7138cf48e09941087e6d9a2e93",
            "taskId": this.internalInfo.taskId,
            "themeTableId": this.themeTableId,
            "productId": this.internalInfo.productId,
            "themeGroupId": this.themeGroupId,
            "themeWordsId": id,
            "themeWordsName": val,
            "checkStatus": 0,
            "createBy": this.server.getuserName()
        }
        this.http.post(url, data)
            .subscribe(res => {
                if (res['result_code'] == '0000') {
                    //成功只提示一次，k==1 , ${val} 
                    if (k === 1) {
                        this.hintsService.messages(`主题词标引成功!`, res['result_code']);
                    }

                    //只有在内文中存在主题词的才执行此方法
                    if(succ == 'succ'){
                        //保存内文加上标记后的内容
                        this._saveProductFileContent(this.internalTablesParam.productId,this.internalContent);
                    }
                    this.server.internalThemeWordsTablesRelEmit.emit(this.taskType);
                } else if(res['result_code'] == '9999'){
                    if(!ir){
                        if (k === 1) {
                            var obj =  $('#internalContents').find('[class="indexing_a"][data-id='+id+']');
                            obj.prop('outerHTML',obj.html());
                            this.hintsService.messages(res['message'], res['result_code']);
                        }
                    }else{
                        //右侧标引时如果已经存在主题词了，还是要标引，但是不要提示
                        //保存内文加上标记后的内容
                        this._saveProductFileContent(this.internalTablesParam.productId,this.internalContent);
                    }
                   
                } else {
                    if (k === 1) {
                        this.hintsService.messages('error', 'error');
                    }
                }
            });
    }

    //保存内文加上标记后的内容
    _saveProductFileContent(productId,FileContent){
       if(productId != '' && FileContent != ''){
          let data = {};
          data['token'] = internal.retrieval.token;
          data['productId'] = productId;
          data['FileContent'] = FileContent;
          let url = this.server.baseUrl + 'Service/IdxProduct/saveProductFileContent';
          this.request
            .postRequest(url, data)
            .then(res => {
                this.getIndexingDetails("0");
                return;
            })
            .catch(err => {
                this.hintsService.messages("error", "error");
                return;
            });
       }
    }

    /**
     * 标引完成提交
     */
    _updateTaskProduct() {
        let data = {};
        data['token'] = internal.retrieval.token;
        data['id'] = this.id;
        data['productId'] = this.internalTablesParam.productId;
        data['taskId'] = this.internalTablesParam.taskId;
        data['status'] = 1;
        data['updateBy'] = this.server.getuserName();
        let url = this.server.baseUrl + 'Service/Task/updateTaskProduct';
        this.request
            .postRequest(url, data)
            .then(res => {
                //this.getIndexingDetails();
                this.hintsService.messages(res.message, res.result_code);
                
                setTimeout(()=>{
                    this.server.closeCurrentPageEimt.emit(this.router.url);
                },1000);

                return;
            })
            .catch(err => {
                this.hintsService.messages("error", "error");
                return;
            });
    }

    getIndexingDetails(isChangeTable = "1") {
        let url = this.server.baseUrl + 'Service/IdxProduct/getIndexingDetails';
        let data = {
            "token": "b25dbd7138cf48e09941087e6d9a2e93",
            // "checkStatus":1,
            "id": this.id,
        };
        this.request.postRequest(url, data).then((res: any) => {
            if (res.result_code === '0000') {
                if(this.taskType == 2){
                        this.internalInfo.name = res.result.idxThemeTable.name;
                        this.internalTablesParam.productId = res.result.idxThemeTable.themeTableId;
                        this.internalTablesParam.themeTableId = res.result.idxThemeTable.themeTableId;
                        this.internalTablesParam.themeTableName = res.result.idxThemeTable.name;
                        this.internalInfo.productId = res.result.idxThemeTable.themeTableId;
                        this.leftKeyword._infoThemeTab(this.internalTablesParam.themeTableId);
                }else{
                    this.internalInfo.productType = res.result.idxProducts.productType;
                    if(res.result.idxProducts.filePath){
                        this.filePath = this.sanitizer.bypassSecurityTrustResourceUrl(res.result.idxProducts.filePath);
                    }
                    
                    if (this.taskType == 0) {
                        if(res.result.idxProducts.filePath){
                            this.fileFormat = res.result.idxProducts.fileFormat;//资源类型
                            if(this.fileFormat == 'mp3'){
                                setTimeout(()=>{
                                    $("#audio-model").attr("src", res.result.idxProducts.filePath);
                                },100)
                                
                            }else if(this.fileFormat == 'mp4'){
                                setTimeout(()=>{
                                 $("#video-model").attr("src", res.result.idxProducts.filePath);
                                },100)
                            }else{
                                const iframe = this.hostElement.nativeElement.querySelector('iframe');
                                iframe.src = res.result.idxProducts.filePath;
                            }
                            
                        }
                        
                        
                    } else if(this.taskType == 1) {
                        //TODO::内文的内容
                        if(res.result.idxProductInnertext){
                            //旧的获取方法
                            this.internalContent = res.result.idxProductInnertext.fileContent;

                            //新的获取方法
                            //xml分页，获取分页数
                            //let internalPageContentList = res.result.idxProductInnertext.fileContent;
                            //this.xmlPageContent(internalPageContentList);
                        }
                    }

                    this.internalInfo.name = res.result.idxProducts.name;
                    this.internalInfo.productId = res.result.productId;
                    this.internalInfo.idxProduct = res.result.idxProduct;
                }
                if(isChangeTable == "1") {
                    this.internalInfo.idxTaskThemeTableList = res.result.idxTaskThemeTableList;
                    this.idxRefTaskThemeTableList = this._cloneObj(res.result.idxTaskThemeTableList);
                    this.TaskThemeTableList = this._tabCanShow(res.result.idxTaskThemeTableList);
                }

                if(!this.themeTableId){
                    this.themeTableId = this.internalInfo.idxTaskThemeTableList[0].themeTableId;
                }
                
                this.themeTableName = this.internalInfo.idxTaskThemeTableList[0].themeTableName;
                this.themeGroupId = this.internalInfo.idxTaskThemeTableList[0].themeGroupId;
                this.internalInfo.taskId = res.result.taskId;
                this.internalInfo.status = res.result.status;
                this.internalInfo.checkStatus = res.result.checkStatus;
                this.internalInfo.refIndexing = res.result.refIndexing;
                this.internalInfo.fileContent = res.result.fileContent;

                this.completeStatus = res.result.mainCompleteStatus;
                this.internalTablesParam.completeStatus = res.result.mainCompleteStatus;

                //模板id
                this.internalInfo.templateId = res.result.templateId;
                this.internalTablesParam.templateId = res.result.templateId;

                //是否已完成标引
                this.internalTablesParam.statusData = res.result.status;
                //是否已审核
                this.internalTablesParam.checkStatusData = res.result.checkStatus;
                
                this.statusData = res.result.status;
                this.checkStatusData = res.result.checkStatus;
                
                //任务审核人
                if(res.result.taskCheckBy == this.server.getuserName()){
                    this.isTaskCheckBy = true;
                }else{
                    this.isTaskCheckBy = false;
                }

                //任务分配的标引人
                if(res.result.idxTaskAssignList){
                    this.isTaskAssignBy = this._isTaskAssignBy(res.result.idxTaskAssignList);
                }
                if(isChangeTable == "1"){
                    this.changeThemeTable(this.themeTableId, this.themeTableName, this.themeGroupId);
                }
                this._getTaskProductList(res.result.taskId);
            } else {
                // this.hintsService._operationHints(res.message,res.result_code);
            }
            // this._cancelChecked();
            return;
        })
            .catch((err: any) => {
                // this.hintsService._operationHints("error","error");
                // this._cancelChecked();
                return;
            });
    }

    //xml分页显示
    contentTotal:number = 0;//总页数
    pageSize:number = 1;//一页显示一条
    pageContent:any = [];
    internalPageContent:any = [];
    xmlPageContent(content:any){
        let contentHtml = $(content).html();
        this.contentTotal = $(contentHtml).length;//标引总页数
        let pageContent:any = [];
        $(contentHtml).each(function(i,v){
            let conHtml = $(this).html();
            pageContent.push(conHtml);
        })

        this.internalPageContent = pageContent;
        this.internalContent = this.internalPageContent[0];
    }

    /**
     * 内文xml分页
     * @param pagination 
     */ 
    internalPageNo: number = 1;
    internalPageSize: number = 1;
    internalNaturalNum: number = 0;
    _internalPagination(pagination: Array<any>) {
        this.internalPageNo = pagination[0].pageNumber;
        this.internalPageSize   = pagination[0].pageSize;
        this.internalNaturalNum = (this.internalPageNo - 1) * this.internalPageSize;
        this.internalContent = this.internalPageContent[this.internalNaturalNum];
    }

    //判断当前用户是否是标引人
    _isTaskAssignBy(idxTaskAssignList){
        for(let i=0;i<idxTaskAssignList.length;i++)
        {
            if(idxTaskAssignList[i]['taskAssignBy'] == this.server.getuserName())
                return true;
        }
        return false;
    }

    //切换主题词表idxThemeTable
    changeThemeTable(id, themeTableName, themeGroupId) {
        if (id) {
            this.timeAttr = false;
            this.Attr = false;
            $("#tab_attribute a").attr('class','');
            $("#tab_time_attribute a").attr('class','');
            $("#tab1").show();
            $("#tab2").hide();
            $("#tab3").hide();

            this.themeTableId = id;
            for(let i = 0;i< this.TaskThemeTableList.length;i++){
                this.TaskThemeTableList[i]['active'] = 0;
                if(this.TaskThemeTableList[i].themeTableId == id){
                    this.TaskThemeTableList[i]['active'] = 1;
                }
            }

            this.themeTableId = id;
            this.themeTableName = themeTableName;
            this.internalTablesParam = {
                taskId: this.internalInfo.taskId,
                productId: this.internalInfo.productId,
                productType: this.taskType,
                themeTableId: this.themeTableId,
                themeTableName: themeTableName,
                themeGroupId: themeGroupId,
                id: this.id,
                completeStatus:this.completeStatus,
                templateId: this.internalInfo.templateId,
                statusData:this.statusData,
                checkStatusData: this.checkStatusData
            };
            this.table.internalParam = this.internalTablesParam;
            // setTimeout(()=>{
            this.server.internalThemeWordsTablesRelEmit.emit(this.taskType);
            // },250);
            
            //切换tab时清空标引输入框中的值
            $("#enterIndexingText").val('');
        }
    }

    viewVersionTable() {
        this.versionTable.internalParam = this.internalTablesParam;
        this.versionTable.currentShowVersionName = '';
        this.versionTable.currentVersionActive = -1;
        this.versionTable.detailTabVal = null;
        this.versionTable.getIndexedVersionTables(1, 20, {}, '');
    }

    /**
    * 任务内容列表
    */
    _getTaskProductList(taskId: any) {

        let params = {
            token: internal.retrieval.token,
            pageNo: 1,
            pageSize: 20,
            taskId: taskId
        };
        this.request.postRequest(this.server.baseUrl + 'Service/Task/getTaskProductList', params).then((res: any) => {
            if (res.result_code === '0000') {
                this.taskProductList = res.result;
            }
            return;
        }).catch((err: any) => {
            this.hintsService.messages("error", "error");
            return;
        });
    }

    //标引的上一篇
    _refereceIndexingTaskPrevious() {
        if (this.taskProductList) {
            let initIndex = this._serialNumber();

            if (this.taskProductList.length !== (Number(initIndex) - 1) && (initIndex !== 0)) {
                initIndex = Number(initIndex) - 1;

                let previousId = this.taskProductList[initIndex]['id'];

                this.router.navigate(['/internal'], {
                    queryParams: { id: previousId, taskType: this.taskType }
                }
                );
            }else{
                this.hintsService.messages('已经是第一篇了！','0000');
            }
        }
    }

    //标引的下一篇
    _refereceIndexingTaskNext() {
        if (this.taskProductList) {
            let initIndex = this._serialNumber();

            if (this.taskProductList.length != (Number(initIndex) + 1) && (this.taskProductList.length != initIndex)) {
                initIndex = Number(initIndex) + 1;

                let nextId = this.taskProductList[initIndex]['id'];

                this.router.navigate(['/internal'], {
                    queryParams: { id: nextId, taskType: this.taskType }
                }
                );
            }else{
                this.hintsService.messages('已经是最后一篇了！','0000');
            }
        }
    }

    //返回上一篇与下一篇的当前任务内文的序号
    _serialNumber() {
        let initIndex = 0;
        if (this.taskProductList) {
            let pid: any = this.id;//当前任务内容id

            let i = 0;
            for (let v of this.taskProductList) {
                if (pid == v['id']) {
                    initIndex = i;
                }
                i++;
            }
        }

        return initIndex;
    }


    _tabCanShow(idxTaskThemeTableList){
        //默认显示5个
        if(idxTaskThemeTableList && idxTaskThemeTableList.length > 0){
            for(let i = 0;i< idxTaskThemeTableList.length;i++){
                idxTaskThemeTableList[i]['active'] = 0;
                if(i < 5){
                    if(i == 0){
                        idxTaskThemeTableList[i]['active'] = 1;
                    }
                    idxTaskThemeTableList[i]['canshow'] = 1;
                }else{
                    idxTaskThemeTableList[i]['canshow'] = 0;
                }
            }
        }
        return idxTaskThemeTableList;
    }

    _moveTab(type){
        if(type == 'plus'){
            if(this.TaskThemeTableList && this.TaskThemeTableList.length > 5){
                if((this.TaskThemeTableList.length - this.currentTabIndex) >= 5){
                    this.currentTabIndex++;
                }
            }
        }else{
            if(this.currentTabIndex > 1){
                this.currentTabIndex--;
            }
        }

        for(let i = 0;i< this.TaskThemeTableList.length;i++){
            this.TaskThemeTableList[i]['canshow'] = 0;
        }

        if(this.TaskThemeTableList && this.TaskThemeTableList.length > 0){
            let n = 0;
            for(let i = (this.currentTabIndex - 1);i< this.TaskThemeTableList.length;i++){
                n++;
                if(n <= 5){
                    this.TaskThemeTableList[i]['canshow'] = 1;
                }else{
                    this.TaskThemeTableList[i]['canshow'] = 0;
                }
            }
        }
    }


   _cloneObj(obj) {
       let newObj = {};
       if (obj instanceof Array) {
           newObj = [];
       }
       for (let key in obj) {
           let val = obj[key];
           newObj[key] = typeof val === 'object' ? this._cloneObj(val) : val;
       }
       return newObj;
   }


    _leftShift() {
        var zuo = $('#myTxtTab li').css("left");
        var kuandu = $("#myTxtTab li").width()+8;
        var zuo02 = parseInt(zuo) + kuandu;
        if(parseInt(zuo) < 0){
            if(parseInt(zuo) <= 0 && parseInt(zuo) >= -106){
                $("#myTxtTab li").animate({left:'0px'});
            }else{
                $("#myTxtTab li").animate({left:zuo02 + 'px'});
            }

        }
    }

    _rightShift() {
        var zuo = $('#myTxtTab li').css("left");
        var you = $('#myTxtTab li').css("right");
        var kuandu = $("#myTxtTab li").width()+8;
        var zuo02 = parseInt(zuo) - kuandu;
        var p = kuandu * $("#myTxtTab li").length;
        if(parseInt(you) < p/2 && p>$("#myTxtTab").width()){
            $("#myTxtTab li").animate({left:zuo02 + 'px'});
        }
    }

    //右键菜单选中
    _rightSelected(){
        if($('.selected-current-contents').length > 0){
            let txt = $('.selected-current-contents').html();
            if (txt != '') {
                this.server.internalRightClickMenuEmit.emit(txt);
                $("#internalModalAutoComplate").modal("show");
            }else{
                this.hintsService.messages('请选中文字内容','9999');
                return false;
            }
        }
    }

    //右键菜单选中
    _rightDateSelected(){
        if($('.selected-current-contents').length > 0){
            let txt = $('.selected-current-contents').html();
            if (txt != '') {
                this.server.internalRightClickMenuEmit.emit(txt);
                $("#internalModalDate").modal("show");
            }else{
                this.hintsService.messages('请选中文字内容','9999');
                return false;
            }
        }
    }

    //删除文内索引
    _deleteIndexingContent(id){
        let obj;
        if(String(id).indexOf(',') !== -1){
            if(String(id).split(',')[1] != 'undefined' && String(id).split(',')[1] != ''){
                obj =  $('#internalContents').find('[class="indexing_a"][data-id='+String(id).split(',')[0]+'][data-order='+String(id).split(',')[1]+']');
            }else{
                obj =  $('#internalContents').find('[class="indexing_a"][data-id='+String(id).split(',')[0]+']');
            }
        }else{
            obj =  $('#internalContents').find('[class="indexing_a"][data-id='+id+']');
        }

        if(obj){
            obj.prop('outerHTML',obj.html());
            this.internalContent = $('#internalContents').html();
            this._saveProductFileContent(this.internalTablesParam.productId,this.internalContent);
        }
    }

    //切换到时间属性
    public timeAttr = false;
    _changTimeAttribute(){
        $('#myTxtTab li a').attr('class','');
        $("#tab1").hide();
        $("#tab2").show();
        $("#tab3").hide();
        this.timeAttr = true;
        this.Attr = false;
    }

    //切换到属性
    public Attr = false;
    _changAttribute(){
        $('#myTxtTab li a').attr('class','');
        $("#tab1").hide();
        $("#tab2").hide();
        $("#tab3").show();
        this.Attr = true;
    }

}
